package com.wentao.mall.api

import com.wentao.mall.dao.PointsHistoryDao
import com.wentao.mall.entity.PageQuery
import com.wentao.mall.entity.ProTableResult
import com.wentao.mall.entity.simple
import org.springframework.data.annotation.CreatedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
import java.util.*
import javax.persistence.*

@RestController
class PointController(
    val pointsHistoryDao: PointsHistoryDao,
) {

    @PostMapping("/admin/pointsHistory/save")
    fun save(@RequestBody pointsHistory: PointsHistory): Result {
        val s = pointsHistoryDao.save(pointsHistory)
        return Result.success()
    }

    @GetMapping("/admin/pointsHistory/list")
    fun list(pageQuery: PageQuery): ProTableResult {
        val page = pointsHistoryDao.findByOrderByDateAddedDesc(pageQuery.toPageRequest())

        return page.simple()
    }

    @PostMapping("/admin/pointsHistory/delete")
    fun delete(id: Int): Result {
        return Result.success(pointsHistoryDao.deleteById(id))
    }

}

data class PointsHistoryDTO(
    val id: Int? = null,
    val openId: String? = null,
    val points: Int?,
    val type: PointsType?,
)

@Entity
@EntityListeners(AuditingEntityListener::class)
data class PointsHistory(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Int? = null,

    val openId: String? = null,

    val points: Int?,
    val type: PointsType?,

    @CreatedDate
    var dateAdded: Date? = null,

    )

enum class PointsType {
    SIGN, INVOICE_UPLOAD, STEP_SETTLE
}

@Entity
@EntityListeners(AuditingEntityListener::class)
data class TodayInfo(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Int = -1,
    val userId: Int,
    val date: String,
    var pointsEarned: Int = 0, // 今日积分

    val stepsFromWx: Int = 0, // 微信步数
) {
    val pointsLeft: Int
        get() = DAY_MAX_POINTS - pointsEarned // 今日剩余积分
}